package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import entity.Exam;
import entity.Student;
import util.DBUtil;

public class ExamDao {
	public static int PAGE_SIZE = 10;

	public List<Exam> paging(int pageNo) {

		String sql = "select * from s_examresult order by id asc limit ?,? ";

		List<Exam> datas = new ArrayList<>();
		Connection con = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			ps = con.prepareStatement(sql);
			ps.setInt(1, PAGE_SIZE * (pageNo - 1));
			ps.setInt(2, PAGE_SIZE);
			rs = ps.executeQuery();
			while (rs.next()) {
				Exam e = new Exam();
				e.setScore(rs.getFloat("score"));
				e.setId(rs.getLong("id"));
				e.setSbId(rs.getLong("sb_id"));
				e.setStId(rs.getLong("st_id"));
				e.setExamName(rs.getString("exam_name"));
				e.setExamDate(rs.getDate("exam_date"));
				datas.add(e);
			}

		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			DBUtil.close(rs);
			DBUtil.close(ps);
			DBUtil.close(con);
		}
		return datas;

	}

	public int getTotalPage() {
		String sql = "select count(*) from s_examresult";

		Connection con = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		Student stu = null;
		int a = 0;
		try {
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			if (rs.next()) {
				a = rs.getInt(1);
			}

		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			DBUtil.close(rs);
			DBUtil.close(ps);
			DBUtil.close(con);
		}
		// int page = (int) Math.ceil(a * 1.0 / PAGE_SIZE);
		int page = a / PAGE_SIZE + (a % PAGE_SIZE == 0 ? 0 : 1);
		return page;

	}
}
